package com.expert.miniapp.controller;

import com.expert.miniapp.dto.LoginRequest;
import com.expert.miniapp.dto.LoginResponse;
import com.expert.miniapp.dto.ResultDTO;
import com.expert.miniapp.service.UserService;
import jakarta.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * AuthController - 认证控制器
 * 提供用户登录相关接口
 *
 * @author System
 * @since 2025-01-14
 */
@RestController
@RequestMapping("/api/auth")
@CrossOrigin(origins = "*")
public class AuthController {

    private static final Logger logger = LoggerFactory.getLogger(AuthController.class);

    @Autowired
    private UserService userService;

    /**
     * 微信小程序登录
     *
     * @param request 登录请求（包含code）
     * @return 登录响应（包含token和用户信息）
     */
    @PostMapping(value = "/wechat/login", produces = "application/json;charset=UTF-8")
    public ResultDTO<LoginResponse> wechatLogin(@Valid @RequestBody LoginRequest request) {
        logger.info("接收到微信登录请求: code={}", request.getCode());

        try {
            LoginResponse response = userService.wechatLogin(request.getCode());
            logger.info("微信登录成功: userId={}, isNewUser={}",
                    response.getUserInfo().getUserId(),
                    response.getIsNewUser());

            return ResultDTO.success(response);

        } catch (Exception e) {
            logger.error("微信登录失败", e);
            return ResultDTO.error("登录失败: " + e.getMessage());
        }
    }
}
